import React, { useState } from "react";
import { Search, Tag, Space } from "react-vant";
import { getList } from "../../api";
import ListItem from "../../components/ListItem";
import { ListRawState } from "../home";
const Index: React.FC = () => {
  const [list, setList] = useState<ListRawState[]>([]);
  const [searchList, setSearchList] = useState<string[]>(["a", "b", "c", "d"]);
  const [show, setShow] = useState(false);
  const handleSearch = async (value: string) => {
    // 请求搜索
    const resp = await getList({ wd: value });
    setList(resp.data.data);

    // 历史记录
    // 追加历史记录(去重)
    setSearchList([...new Set([value, ...searchList])]);

    // 切换状态
    setShow(true);
  };

  return (
    <div className="search">
      <Search
        onSearch={(value) => handleSearch(value)}
        onClear={() => setShow(false)}
      ></Search>
      {show ? (
        <div>
          {list.length > 0 ? (
            list.map((v) => {
              return <ListItem key={v.id} v={v}></ListItem>;
            })
          ) : (
            <div className="not-found">暂无搜索结果！！！</div>
          )}
        </div>
      ) : (
        <div className="search-list">
          <h4>
            <span>搜索记录</span>
            <span onClick={() => setSearchList([])}>删除</span>
          </h4>
          <Space>
            {searchList.map((v, i) => {
              return <Tag key={i}>{v}</Tag>;
            })}
          </Space>
        </div>
      )}
    </div>
  );
};

export default Index;
